package com.st.springbootsse.controller;

import cn.hutool.core.util.IdUtil;
import com.st.springbootsse.service.IndexService;
import com.st.springbootsse.utils.SseClient;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author zhangli
 */
@Controller
public class IndexActionControllrt {
    @Autowired
    private SseClient sseClient;

    @Resource
    private IndexService indexService;

    @GetMapping("/")
    public String index(ModelMap model) {
        String uid = IdUtil.fastUUID();
        model.put("uid", uid);
        return "index";
    }

    /**
     * 创建sse连接
     *
     * @param uid
     * @return
     */
    @CrossOrigin
    @GetMapping("/createSse")
    public SseEmitter createConnect(String uid) {
        // 创建sse连接
        SseEmitter sse = sseClient.createSse(uid);
        // 发送消息
        indexService.sendMessage(uid);
        return sse;
    }

/*
    @CrossOrigin
    @GetMapping("/sendMsg")
    @ResponseBody
    public String sseChat(String uid) {
        for (int i = 0; i < 10; i++) {
            sseClient.sendMessage(uid, "no" + i, IdUtil.fastUUID());
        }
        return "ok";
    }
    */


    /**
     * 关闭sse连接
     *
     * @param uid
     */
    @CrossOrigin
    @GetMapping("/closeSse")
    public void closeConnect(String uid) {
        System.out.println("关闭sse连接");
        indexService.closeSse(uid);
        sseClient.closeSse(uid);
    }
}